local respond_to      = require("lapis.application").respond_to
local csrf_tool       = require("utils.csrf_tool")
local capture_errors  = require("lapis.application").capture_errors
local object          = require("controllers.userController")

return respond_to({
	GET = function(self)
		if self.session.user then
			self.head_title = "Editar perfil"

			-- Genera un token contra ataques CSRF con tiempo de expiración.
			self.csrf_token = csrf_tool.generate_token(self)

			-- Obtiene datos que únicamente un usuario puede modificar.
			self.profile = object:userProfile(self.session.user.username)

			if self.session.message then
				self.message         = self.session.message
				self.session.message = nil
			end

			-- Formatos de imagen permitidos en el formulario.
			local image_formats      = require("utils.website_config").image_formats
			self.max_image_size      = require("utils.website_config").max_image_size
			self.valid_image_formats = ""

			for index,format in ipairs(image_formats) do
				self.valid_image_formats = self.valid_image_formats.."image/"..format..","
			end

			-- Elimina la "," del final.
			self.valid_image_formats = string.sub(self.valid_image_formats,1,-2)

			return { render = "pages.edit_profile" }
		else
			return { redirect_to = self:url_for("index") }
		end
	end,
	POST = capture_errors({
		-- Captura y muestra fallos (excepciones) dentro de una plantilla.
		on_error = require('utils.errors'),
		function(self)
			if self.session.user then
				-- Autentifica y valida el tiempo de expiración del token.
				csrf_tool.validation_token(self)

				-- Selecciona los campos de un formulario que solo son necesarios y
				-- elimina espacios sobrantes de inicio y fin.
				local inputs_form = { "name", "username", "password", "password_confirm", "description" }

				local trim = require("lapis.util").trim
				local data = {}

				for index,input in ipairs(inputs_form) do
					data[input] = trim(self.params[input])
				end

				-- Valida los campos de un formulario.			
				local validate = require("utils.validate")

				if self.params.avatar then
					if self.params.avatar.content ~= "" then
						data.avatar = self.params.avatar

						validate.assert_valid(data, {{ "avatar", is_file = true, is_image = true }})
					end
				end

				if self.params.background then
					if self.params.background.content ~= "" then
						data.background = self.params.background

						validate.assert_valid(data, {{ "background", is_file = true, is_image = true }})
					end
				end

				validate.assert_valid(data, {
					{ "description",      optional = true, min_length = 1, max_length = 255, type       = "string" },
					{ "name",             optional = true, min_length = 5, max_length = 255, type       = "string" },
					{ "username",         optional = true, min_length = 1, max_length = 255, not_spaces = true, is_username = true, type = "string" },
					{ "password",         optional = true, min_length = 6, max_length = 255, not_spaces = true, type        = "string" },
					{ "password_confirm", equals = data.password }
				})

				-- Edita los datos de un perfil de usuario.
				self.session.message = object:userEdit(self.session.user, data)

				return { redirect_to = self:url_for("edit_profile") }
			else
				return { redirect_to = self:url_for("index") }
			end
		end
	})
})